package com.lebang.controller.api.donwn;

import com.alibaba.fastjson.JSONObject;
import com.lebang.common.Require;
import com.lebang.component.RedisClient;
import com.lebang.entity.RequestHeaders;
import com.lebang.service.*;
import com.lebang.service.earn.AppRousePlanDetailService;
import com.lebang.service.sys.AdSwitchConfigService;
import com.lebang.service.sys.DictService;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

/**
 * @Author: hwq
 * @Date: 2020/3/16 13:33
 * @Version 1.0
 */
@Api(tags = "每日必赚广告位控制")
@RestController
@RequestMapping("/app/ad")
@Slf4j
public class AppAdController {
    @Autowired
    private AppRouseAdService appRouseAdService;
    @Autowired
    private DownAppService downAppService;
    @Autowired
    private AppAdControService appAdControService;
    @Autowired
    private AppRousePlanDetailService appRousePlanDetailService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private MemberSdkBannedService memberSdkBannedService;
    @Autowired
    private AdSwitchConfigService adSwitchConfigService;
    @Autowired
    private DictService dictService;
    /**
     * 根据数据源key获取广告位
     *
     * @param request
     * @param key
     * @return
     */
    @ApiParam("根据key获取广告位")
    @GetMapping("/earn/{key}")
    @Require
    public JsonData get(HttpServletRequest request, @PathVariable String key) {
        RequestHeaders header = new RequestHeaders(request);
        if(dictService.selectIntByKeyName("ad_switch_type")==0){
            int count = appRouseAdService.getCountByKey(key);
            Optional<String> adId = appRouseAdService.selectAdIdByKey(key, count,header.getAppStore());
            return adId.map(s -> Callback.success("200", "查询成功", s))
                    .orElse(Callback.fail("200", "查询失败key不存在"));
        }else {
            int count = downAppService.getAllCountBySdkKey(header,key);
            Optional<String> adId = adSwitchConfigService.selectAdIdByRequest(header,count,key);
            return adId.map(s -> Callback.success("200", "查询成功", s))
                    .orElse(Callback.fail("200", "查询失败key不存在"));
        }

    }

    /**
     * 数据源广告位增加次数
     *
     * @param request
     * @param key
     * @return
     */
    @Require
    @PutMapping("/earn/{key}")
    public JsonData put(HttpServletRequest request, @PathVariable String key) {
        if (downAppService.selectByKey(key) == null) {
            return Callback.fail("200", "key不存在");
        }
        appRouseAdService.addCountByKey(key);
        return Callback.success("success", "操作成功");
    }


    /**
     * 根据广告位获取数据源
     *
     * @param request
     * @param key
     * @return
     */
    @Require
    @ApiParam("根据广告位获取数据源")
    @GetMapping("/allad/{key}")
    public JsonData getByAll(HttpServletRequest request, @PathVariable String key) {
       // long star=System.currentTimeMillis();
        RequestHeaders header = new RequestHeaders(request);
        List<String> record=memberSdkBannedService.getRecord(header.getUserid());
        boolean exits=appAdControService.checkAppStore(key,header.getAppStore());
        int count;
        if(exits){
             count = appAdControService.getCountByKey(key,header.getAppStore());
        }else {
             count = appAdControService.getCountByKey(key);
        }
        List<String> filterSdkKey=downAppService.filterSdkKey(header.getUserid());
        filterSdkKey.addAll(record);
        Optional<String> sdkKey = appAdControService.selectAdIdByKey(key, count,header.getAppStore());
        JSONObject jsonObject = new JSONObject();
        if (!sdkKey.isPresent()) {
            jsonObject.put("sdkKey", "ABC");
            jsonObject.put("adId","ABC");
           // log.info("2001--->"+header.getUserid()+"-------->"+key+"请求耗时:"+(System.currentTimeMillis()-star));
            return Callback.success("2001", "查询成功", jsonObject);

        }
        if (appRousePlanDetailService.check(sdkKey.get())) {
            sdkKey = Optional.ofNullable(appRousePlanDetailService.getKeyByCount(sdkKey.get(), header.getUserid(),filterSdkKey));
        }
        if (!sdkKey.isPresent()) {
            jsonObject.put("sdkKey", "ABC");
            jsonObject.put("adId","ABC");
          //  log.info("2002--->"+header.getUserid()+"-------->"+key+"请求耗时:"+(System.currentTimeMillis()-star));
            return Callback.success("2002", "查询成功", jsonObject);
        }

        //按权重
        if ("random".equals(sdkKey.get())) {
            sdkKey = downAppService.getRandomAdStringKey(header, Integer.parseInt(header.getVersion()), 0,filterSdkKey);
        }
        if (!sdkKey.isPresent()) {
            jsonObject.put("sdkKey", "ABC");
            jsonObject.put("adId","ABC");
           // log.info("2003--->"+header.getUserid()+"-------->"+key+"请求耗时:"+(System.currentTimeMillis()-star));
            return Callback.success("2003", "查询成功", jsonObject);
        }
        if ("NULL".equals(sdkKey.get())||filterSdkKey.contains(sdkKey.get())) {
            jsonObject.put("sdkKey", "ABC");
            jsonObject.put("adId","ABC");
          //  log.info("2004--->"+header.getUserid()+"-------->"+key+"请求耗时:"+(System.currentTimeMillis()-star));
            return Callback.success("2004", "查询成功", jsonObject);
        }
//        count = appRouseAdService.getCountByKey(sdkKey.get());
//        Optional<String> adId = appRouseAdService.selectAdIdByKey(sdkKey.get(), count,header.getAppStore());
        Optional<String> adId;
        if(dictService.selectIntByKeyName("ad_switch_type")==0){
             count = appRouseAdService.getCountByKey(sdkKey.get());
             adId = appRouseAdService.selectAdIdByKey(sdkKey.get(), count,header.getAppStore());

        }else {
             count = downAppService.getAllCountBySdkKey(header,sdkKey.get());
            adId = adSwitchConfigService.selectAdIdByRequest(header,count,sdkKey.get());

        }
        if (!adId.isPresent()) {
            jsonObject.put("sdkKey", "ABC");
            jsonObject.put("adId","ABC");
         //   log.info("201--->"+header.getUserid()+"-------->"+key+"请求耗时:"+(System.currentTimeMillis()-star));
            return Callback.success("201", "查询成功", jsonObject);
        }
        jsonObject.put("sdkKey", sdkKey.get());
        jsonObject.put("adId", adId.get());
      //  log.info("200--->"+header.getUserid()+"-------->"+key+"请求耗时:"+(System.currentTimeMillis()-star));
        return Callback.success("200", "查询成功", jsonObject);

    }

    /**
     * 增加广告位观看次数
     *
     * @param request
     * @param key
     * @return
     */
    @Require
    @PutMapping("/allad/{key}")
    public JsonData putByAll(HttpServletRequest request, @RequestHeader("userid") String memberId ,
                             @RequestHeader("appStore") String appStore ,@PathVariable String key, String sdkKey) {
        appAdControService.addCountByKey(key, sdkKey,appStore,memberId);
        return Callback.success("success", "操作成功");
    }
}
